import { defineStore } from 'pinia'
import { ref, computed, reactive } from 'vue'
import {
    startServer as startSocketServer,
    stopServer as stopSocketServer
} from '@/utils/socket'
import { submitPapersToPlatform } from '@/utils/api'

export const useExamStore = defineStore('exam', () => {
    // 状态定义
    const state = reactive({
        serverStatus: 'stopped', // 'stopped' | 'running' | 'error'
        connectedStudents: [],
        submittedPapers: [],
        lastRefresh: null,
        error: null
    })

    // 计算属性
    const connectedCount = computed(() => state.connectedStudents.length)
    const submittedCount = computed(() => state.submittedPapers.length)
    const activeStudents = computed(() =>
        state.connectedStudents.filter(s => s.status === 'connected'))
    const lastRefreshTime = computed(() =>
        state.lastRefresh ? new Date(state.lastRefresh).toLocaleTimeString() : '从未刷新')

    // 操作方法
    const startServer = async () => {
        try {
            state.serverStatus = 'running'
            state.error = null

            await startSocketServer({
                onConnection: handleStudentConnect,
                onHeartbeat: handleHeartbeat,
                onSubmission: handlePaperSubmission
            })

            state.lastRefresh = new Date()
        } catch (error) {
            state.serverStatus = 'error'
            state.error = error.message
            console.error('服务器启动失败:', error)
            throw error
        }
    }

    const stopServer = async () => {
        try {
            await stopSocketServer()
            state.serverStatus = 'stopped'
            state.error = null
        } catch (error) {
            state.error = error.message
            console.error('服务器停止失败:', error)
            throw error
        }
    }

    const refreshData = async () => {
        try {
            // 这里可以添加从服务器获取最新数据的逻辑
            state.lastRefresh = new Date()
        } catch (error) {
            state.error = error.message
            console.error('数据刷新失败:', error)
            throw error
        }
    }

    // 学生连接处理
    const handleStudentConnect = (student) => {
        const existingIndex = state.connectedStudents.findIndex(s => s.id === student.id)
        if (existingIndex >= 0) {
            state.connectedStudents[existingIndex] = {
                ...state.connectedStudents[existingIndex],
                ...student,
                lastHeartbeat: new Date(),
                status: 'connected'
            }
        } else {
            state.connectedStudents.push({
                ...student,
                lastHeartbeat: new Date(),
                status: 'connected'
            })
        }
    }

    // 心跳处理
    const handleHeartbeat = (studentId) => {
        const student = state.connectedStudents.find(s => s.id === studentId)
        if (student) {
            student.lastHeartbeat = new Date()
            student.status = 'connected'
        }
    }

    // 试卷提交处理
    const handlePaperSubmission = (paper) => {
        const existingIndex = state.submittedPapers.findIndex(p => p.id === paper.id)
        if (existingIndex === -1) {
            state.submittedPapers.push(paper)

            // 更新学生状态
            const student = state.connectedStudents.find(s => s.id === paper.studentId)
            if (student) {
                student.status = 'submitted'
            }
        }
    }

    // 打包并上传试卷
    const packageAndUploadPapers = async () => {
        if (state.submittedPapers.length === 0) {
            const error = new Error('没有可提交的试卷')
            state.error = error.message
            throw error
        }

        try {
            const response = await submitPapersToPlatform(state.submittedPapers)
            state.error = null
            return response
        } catch (error) {
            state.error = error.message
            console.error('试卷上传失败:', error)
            throw error
        }
    }

    // 重置考试数据
    const resetExamData = () => {
        state.connectedStudents = []
        state.submittedPapers = []
        state.error = null
    }

    return {
        // 状态
        state,
        // 计算属性
        connectedCount,
        submittedCount,
        activeStudents,
        lastRefreshTime,
        // 方法
        startServer,
        stopServer,
        refreshData,
        packageAndUploadPapers,
        resetExamData
    }
})
